import React, {Component} from "react";
import {Badge, Card, Input, message, Modal, Select, Table, Tooltip, Button, Icon, Transfer} from 'antd';
import {connect} from "dva";
import SearchForm from '../../components/AutoForm/SearchForm';
import EditForm from '../../components/AutoForm/EditForm';

const {Option} = Select;
const confirm = Modal.confirm;
const statusMap = ['processing', 'warning'];
const status = ['使用中', '锁定'];
@connect(({userList, company,loading}) => ({
  tableLoading: loading.effects['userList/page'],
  modalInsertLoading: loading.effects['userList/insert'],
  modalUpdateLoading: loading.effects['userList/update'],
  modalTransferLoading: loading.effects['userList/saveUserRoles'],
  searchForm: userList.searchForm,
  modalForm: userList.modalForm,
  addForm: userList.addForm,
  modalVisible: userList.modalVisible,
  tableData: userList.list,
  selection: userList.selection,
  pagination: userList.pagination,
  optFlag: userList.optFlag,
  transferVisible: userList.transferVisible,
  rolesData: userList.rolesData,
  rolesTargetKeys: userList.rolesTargetKeys,
  transferTitle: userList.transferTitle,
  activeUserId: userList.activeUserId,
  compOptions: company.compOptions,
}))
export default class List extends Component {

  componentDidMount() {
    const {dispatch, pagination} = this.props;
    dispatch({
      type: 'userList/page',
      payload: pagination
    });
    dispatch({
      type: 'company/getCompOptions'
    })
  }

  handleSearch = (page) => {
    const {dispatch, pagination, searchForm} = this.props;
    let pageParam = {pageSize: pagination.pageSize, current: pagination.current}
    if (page) {
      pageParam = {pageSize: page.pageSize, current: page.current}
    }
    let searchValue = {};
    Object.keys(searchForm).map((key) => {
      searchValue[key] = searchForm[key]['value'];
    })
    const param = {
      ...searchValue,
      ...pageParam
    };
    dispatch({
      type: 'userList/page',
      payload: param
    })
  }

  handleSearchChange = (fields) => {
    const {dispatch} = this.props;
    dispatch({
      type: 'userList/handleSearchChange',
      payload: fields
    })
  }

  handleModalVisible = (opt) => {
    const {dispatch, modalVisible,  selection, addForm} = this.props;
    let payload = {modalVisible: !modalVisible};
    let modalForm = {};
    if ('edit' === opt) {
      if (JSON.stringify(selection) === '{}') {
        message.error('请选择一条记录');
        return;
      } else {
        Object.keys(selection).map((key) => {
          modalForm[key] = {value: selection[key]}
        })
      }
    } else if ("add" === opt) {
      Object.keys(addForm).map((key) => {
        modalForm[key] = {value: addForm[key]}
      })
    }

    if (!modalVisible) {
      payload.optFlag = opt;
      payload.modalForm = modalForm;
    }
    dispatch({
      type: 'userList/handleModalVisible',
      payload: payload
    })
  }

  handleModalChange = (fields) => {
    const {dispatch, optFlag, addForm} = this.props;
    const payload = {fields: fields, optFlag: optFlag, addForm: addForm};
    dispatch({
      type: 'userList/handleModalChange',
      payload: payload
    })
  };

  handleOk = (fields) => {
    const {dispatch, optFlag, searchForm, pagination} = this.props;
    let searchValue = {};
    Object.keys(searchForm).map((key) => {
      searchValue[key] = searchForm[key]['value'];
    })
    const payload = {
      fields: fields,
      searchForm: searchValue,
      pagination: pagination
    }
    if (optFlag === 'add') {
      dispatch({
        type: 'userList/insert',
        payload: payload
      })
    } else if (optFlag === 'edit') {
      dispatch({
        type: 'userList/update',
        payload: payload
      })
    }
  };

  handleDel = () => {
    const {dispatch, selection, searchForm, pagination } = this.props;
    if (JSON.stringify(selection) === '{}') {
      message.error('请选择一条记录');
      return;
    }
    let searchValue = {};
    Object.keys(searchForm).map((key) => {
      searchValue[key] = searchForm[key]['value'];
    })
    const payload = {
      fields: selection,
      searchForm: searchValue,
      pagination: pagination
    }
    confirm({
      title: '是否确认删除此用户?',
      content: `账号：${selection.userName}; 中文名：${selection.chName}`,
      okText: '确认',
      cancelText: '取消',
      onOk() {
        dispatch({
          type: 'userList/del',
          payload: payload,
        });
      },
      onCancel() {
      },
    });
  }

  onSelect = (record)=> {
    const {dispatch} = this.props;
    dispatch({
      type: 'userList/handleTableSelection',
      payload: record
    })
  };

  handleTableChange = (pagination) => {
    this.handleSearch(pagination);
  };

  filterOption = (inputValue, option) => option.description.toUpperCase().indexOf(inputValue.toUpperCase()) > -1;

  handleTransferChange = targetKeys => {
    const {dispatch} = this.props;
    dispatch({
      type: 'userList/handleTransferChange',
      payload: targetKeys
    })
  };

  handleTransferVisible = () => {
    const {dispatch,transferVisible} = this.props;
    dispatch({
      type: 'userList/handleTransferVisible',
      payload: !transferVisible
    })
  }
  handleRolesTransfer = (text, record, index) => {
    const {dispatch} = this.props;
    dispatch({
      type: 'userList/getTransfer',
      payload: {compCode: record.compCode, userId: record.id}
    }).then(() => {
        this.handleTransferVisible();
    })
    dispatch({
      type: 'userList/handleTransferTitleChange',
      payload: `分配角色(用户名：${record.userName}，中文名：${record.chName})`
    })
    dispatch({
      type: 'userList/handleActiveUserChange',
      payload: record.id
    })
  };
  handleTransferOk = () => {
    const {dispatch, activeUserId, rolesTargetKeys} = this.props;
    this.handleTransferVisible();
    let userRoles = {userId: activeUserId, roleIds: rolesTargetKeys}
    dispatch({
      type: 'userList/saveUserRoles',
      payload: userRoles
    })
  }
  render() {
    const {
      pagination,
      tableLoading,
      modalInsertLoading,
      modalUpdateLoading,
      modalTransferLoading,
      tableData,
      modalVisible,
      modalForm,
      searchForm,
      optFlag,
      transferVisible,
      rolesData,
      rolesTargetKeys,
      transferTitle,
      compOptions,
    } = this.props;

    const options = compOptions.map(d => <Option key={d.value} value={d.value}>{d.label}</Option>);

    const columns = [
      {
        key: 1,
        title: '序号',
        width: "50px",
        render: (text, record, index) => `${index + 1}`,
      },
      {
        title: '用户名',
        width: "150px",
        dataIndex: 'userName',
      },
      {
        title: '手机号',
        width: "120px",
        dataIndex: 'phone',
      },
      {
        title: '中文名',
        width: '130px',
        dataIndex: 'chName',
      },
      {
        title: '公司编码',
        width: "120px",
        dataIndex: 'compCode',
      },
      {
        title: '电子邮箱',
        width: "200px",
        dataIndex: 'email',
      },
      {
        title: '授权到期时间',
        width: "200px",
        dataIndex: 'authExpTime',
      },
      {
        title: '帐号启用时间',
        width: "200px",
        dataIndex: 'nbfTime'
      },
      {
        title: 'TOKEN过期秒数',
        width: '120px',
        dataIndex: 'tokenExp'
      },
      {
        title: '锁定/使用',
        width: "120px",
        dataIndex: 'isLock',
        render(val) {
          return <Badge status={statusMap[val]} text={status[val]}/>;
        },
      },
      {
        title: '操作',
        fixed: 'right',
        width: '120px',
        render: (text, record, index) => {
          return(
            <div>
              <Tooltip title="角色分配"><Button onClick={() => this.handleRolesTransfer(text, record, index)} shape="circle" size="small"><Icon type="key"/></Button></Tooltip>
            </div>
          )
        },
      }
    ];

    const searchFields = [
      {
        cols: [
          {
            md: 6,
            label: '用户名',
            name: 'userName',
            component: <Input placeholder="请输入"/>
          },
          {
            md: 6,
            label: '手机号',
            name: 'phone',
            component: <Input placeholder="请输入"/>
          },
          {
            md: 6,
            label: '所属公司',
            name: 'compCode',
            component: <Select>{options}</Select>
          },
          {
            md: 6,
            label: '使用状态',
            name: 'isLock',
            component: <Select placeholder="请选择" style={{width: '100%'}}>
              <Option value="0">使用中</Option>
              <Option value="1">锁定</Option>
            </Select>
          }
        ]
      }
    ]
    const EditRows = [
      {
        cols: [
          {
            label: '用户名',
            name: 'userName',
            md: 18,
            rules: [{required: true, message: '请输入至少四个字符！', min: 4}],
            component: <Input disabled={optFlag === 'add' ? false : true} placeholder="请输入用户名"/>
          },
        ]
      },
      {
        cols: [
          {
            label: '手机号',
            name: 'phone',
            md: 18,
            rules: [{required: true, message: '请输入正确的手机号！'}, {pattern: /^1\d{10}$/, message: '请输入正确的手机号！'}],
            component: <Input disabled={optFlag === 'add' ? false : true} placeholder="手机号"/>
          },
        ]
      },
      {
        cols: [
          {
            label: '中文名',
            name: 'chName',
            md: 18,
            component: <Input placeholder="请输入手机号"/>
          }
        ]
      },
      {
        cols: [
          {
            label: '公司编码',
            name: 'compCode',
            md: 18,
            rules: [{required: true, message: '请选择公司！'}],
            component: <Select>{options}</Select>
          }
        ]
      },
      {
        cols: [
          {
            label: '电子邮箱',
            name: 'email',
            md: 18,
            rules: [{pattern: /^([0-9A-Za-z\-_\.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/g, message: '请输入正确的电子邮箱'}],
            component: <Input placeholder="请输入电子邮箱"/>
          }
        ]
      },
      {
        cols: [
          {
            label: 'TOKEN过期秒数',
            name: 'tokenExp',
            md: 18,
            rules: [{
              required: true,
              message: '请输入秒数！'
            }],
            component: <Input type="number" placeholder="请输入TOKEN过期秒数"/>
          },
          {
            name: 'id',
            component: <Input type="hidden"/>
          }
        ]
      },
    ]

    const showTotal = (total) => {
      return `总记录： ${total} 条`;
    }
    pagination.showTotal = showTotal;
    const rowSelection = {
      type: "radio",
      onSelect: this.onSelect
    };

    return (
      <Card bodyStyle={{padding: 0}}>
        <SearchForm
          header="系统用户->操作"
          layout="inline"
          fields={searchFields}
          fieldValue={searchForm}
          onSubmit={this.handleSearch}
          onModal={this.handleModalVisible}
          onFieldsChange={this.handleSearchChange}
          onDel={this.handleDel}
        />
        <Table
          pagination={pagination}
          columns={columns}
          loading={tableLoading}
          dataSource={tableData}
          rowSelection={rowSelection}
          rowKey={record => record.id}
          scroll={{x: 'max-content'}}
          size="small"
          onChange={this.handleTableChange}
          bordered
        />

        <EditForm
          rows={EditRows}
          fieldValue={modalForm}
          onFieldsChange={this.handleModalChange}
          optFlag={optFlag}
          visible={modalVisible}
          onOk={this.handleOk}
          onCancel={this.handleModalVisible}
          confirmLoading={modalInsertLoading || modalUpdateLoading}
        />
        <Modal
          width= "660px"
          visible={transferVisible}
          title={transferTitle}
          okText="确定"
          cancelText="取消"
          onCancel={this.handleTransferVisible}
          onOk={this.handleTransferOk}
          confirmLoading={modalTransferLoading}
        >
          <Transfer
            dataSource={rolesData}
            showSearch
            listStyle={{height: "600px", width: "240px"}}
            filterOption={this.filterOption}
            targetKeys={rolesTargetKeys}
            onChange={this.handleTransferChange}
            render={item => item.title}
          />
        </Modal>
      </Card>
    )
  }
}
